package com.xchb.im.server.init;

import com.xchb.im.server.config.AppConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;

import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheEvent;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.RetryNTimes;

import org.apache.zookeeper.Watcher;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;



/**
 * @author XDD
 * @project muchat
 * @date 2021/7/23
 * @description Good Good Study,Day Day Up.
 */
@Component
@Slf4j
public class Zkinit implements ApplicationListener<ApplicationStartedEvent> {


    @Value("${app.zk.addreess}")
    private String zk_address;

    @Value("${app.zk.path}")
    private String path;


    @SneakyThrows
    @Override
    public void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {
        CuratorFramework client = CuratorFrameworkFactory.newClient(zk_address,
                new RetryNTimes(10, 5000));
        client.start();

        //监听子节点
        PathChildrenCache pathChildrenCache = new PathChildrenCache(client, path,true);

        String listenerPath = path;
        PathChildrenCacheListener pathChildrenCacheListener = new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                ChildData childData = event.getData();
                if (childData != null) {
                    if(PathChildrenCacheEvent.Type.CHILD_ADDED==event.getType()){
                        log.info("新的机器上线:{}", childData.getPath());
                        String path = childData.getPath().replace(listenerPath+"/", "");
                        AppConst.NODE_LIST.add(path);
                    }else if(PathChildrenCacheEvent.Type.CHILD_REMOVED==event.getType()){
                        log.info("机器下线：{}", childData.getPath());
                        String path = childData.getPath().replace(listenerPath+"/", "");
                        AppConst.NODE_LIST.remove(path);
                    }
                }
            }
        };

        pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
        pathChildrenCache.start();
        AppConst.NODE_LIST.addAll(client.getChildren().forPath(path));
    }
}
